package com.diorsunion.hedge.client.io.netty;

import com.diorsunion.hedge.io.netty.KryoDecoder;
import com.diorsunion.hedge.io.netty.KryoEncoder;
import com.diorsunion.hedge.io.netty.KryoPool;
import com.diorsunion.hedge.io.netty.NettyChannelInitializer;
import io.netty.handler.timeout.IdleStateHandler;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;

import javax.annotation.Resource;

/**
 * Created by dingshan.yyj on 2016/5/26.
 */
@Configuration
@PropertySource("classpath:netty-client.properties")
public class NettyClientConfig {

    @Value("${kryo.pool.maxTotal}")
    int maxTotal;
    @Value("${kryo.pool.minIdle}")
    int minIdle;
    @Value("${kryo.pool.maxWaitMillis}")
    long maxWaitMillis;
    @Value("${kryo.pool.minEvictableIdleTimeMillis}")
    long minEvictableIdleTimeMillis;

    @Value("${netty.idle.reader}")
    int readerIdleTimeSeconds;
    @Value("${netty.idle.writer}")
    int writerIdleTimeSeconds;
    @Value("${netty.idle.all}")
    int allIdleTimeSeconds;

    @Resource
    NettyClientHandler nettyClientHandler;

    @Bean(name = "NettyChannelInitializer")
    public NettyChannelInitializer getProtocolInitalizer(){
        KryoPool kryoPool = new KryoPool(maxTotal,minIdle,maxWaitMillis,minEvictableIdleTimeMillis);
        NettyChannelInitializer protocolInitalizer =
                new NettyChannelInitializer(
                        kryoPool,
                        nettyClientHandler,
                        readerIdleTimeSeconds, writerIdleTimeSeconds, allIdleTimeSeconds);
        return protocolInitalizer;
    }

    @Bean
    public static PropertySourcesPlaceholderConfigurer propertyConfigInDev() {
        return new PropertySourcesPlaceholderConfigurer();
    }
}
